package KylinComponents

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"os"
	"time"
)

type logger struct {
	LogType    string
	LogTime    string
	LogContent string
}

//var maxLogCache int
//var infoLog []string
//var errorLog []string

func LogInfo(c *gin.Context, contents ...string) {
	var result string
	if c != nil {
		result = c.ClientIP() + ":" + c.GetString("reqId")
	}
	for _, content := range contents {
		result += " [" + content + "] "
	}
	//infoLog = append(infoLog, result)
	Storage("info", result)
}

func LogDebug(c *gin.Context, contents ...string) {
	var result string
	if c != nil {
		result = c.ClientIP() + ":" + c.GetString("reqId") + ":" + c.Request.RequestURI + ":" + jsonMar(c.Request.Form)
	}

	for _, content := range contents {
		result += " [" + content + "] "
	}
	cfg := InitConfigFromToml()
	ifDebug, _ := cfg.GetValue("APP", "debug")
	if ifDebug == "true" {
		Storage("debug", result)
	}
}

func LogError(c *gin.Context, contents ...string) {
	var result string
	if c != nil {
		result = c.ClientIP() + ":" + c.GetString("reqId")
	}
	for _, content := range contents {
		result += " [" + content + "] "
	}
	Storage("error", result)
}

func Storage(logType string, content string) {
	timeTag := time.Now().Format("2006-01-02 15:04:05")
	timeDate := time.Now().Format("2006-01-02")
	var filename string
	switch logType {
	case "info":
		filename = "Storage/logs/" + timeDate + "-info.log"
	case "error":
		filename = "Storage/logs/" + timeDate + "-error.log"
	case "debug":
		filename = "Storage/logs/" + timeDate + "-debug.log"

	}

	fp, _ := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
	content = "[" + timeTag + "]: " + content + "\n"
	_, err := fp.Write([]byte(content))
	if err != nil {
		fmt.Println("日志写入失败：", err)
	}
	_ = fp.Close()

}

func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}

func jsonMar(data interface{}) string {
	d, err := json.Marshal(data)
	if err != nil {
		return fmt.Sprintf("%s", err)
	}
	return string(d)
}
